package plus.easydo.server.user.mp.controller;

import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import plus.easydo.core.result.R;
import plus.easydo.server.user.mp.constant.Constants;
import plus.easydo.server.user.mp.constant.UserConstants;
import plus.easydo.server.user.mp.entity.SysMenu;
import plus.easydo.server.user.mp.service.ISysMenuService;
import plus.easydo.server.user.mp.vo.RouterVo;
import plus.easydo.server.user.mp.vo.TreeSelect;
import plus.easydo.starter.log.annotation.SystemLog;
import plus.easydo.starter.mybatis.plus.base.MPBaseController;
import plus.easydo.starter.oauth.core.utils.Oauth2Utils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 菜单信息
 *
 * @author ruoyi
 */
@Api(tags = "菜单信息")
@RestController
@RequestMapping("/menu")
public class SysMenuController extends MPBaseController {
    @Autowired
    private ISysMenuService menuService;

    /**
     * 获取菜单列表
     */
    @PreAuthorize("hasPermission('system:menu:list')")
    @GetMapping("/list")
    public R<List<SysMenu>> list(SysMenu menu) {
        Long userId = Oauth2Utils.getUserIdLong();
        List<SysMenu> menus = menuService.selectMenuList(menu, userId);
        return ok(menus);
    }

    /**
     * 根据菜单编号获取详细信息
     */
    @PreAuthorize("hasPermission('system:menu:query')")
    @GetMapping(value = "/{menuId}")
    public R<SysMenu> getInfo(@PathVariable Long menuId) {
        return ok(menuService.selectMenuById(menuId));
    }

    /**
     * 获取菜单下拉树列表
     */
    @GetMapping("/treeselect")
    public R<List<TreeSelect>> treeselect(SysMenu menu) {
        Long userId = Oauth2Utils.getUserIdLong();
        List<SysMenu> menus = menuService.selectMenuList(menu, userId);
        return ok(menuService.buildMenuTreeSelect(menus));
    }

    /**
     * 加载对应角色菜单列表树
     */
    @GetMapping(value = "/roleMenuTreeselect/{roleId}")
    public Map<String, Object> roleMenuTreeselect(@PathVariable("roleId") Long roleId) {
        Long userId = Oauth2Utils.getUserIdLong();
        List<SysMenu> menus = menuService.selectMenuList(userId);
        Map<String, Object> map = new HashMap<>(4);
        map.put("checkedKeys", menuService.selectMenuListByRoleId(roleId));
        map.put("menus", menuService.buildMenuTreeSelect(menus));
        return map;
    }

    /**
     * 新增菜单
     */
    @SystemLog(value = "新增菜单",saveLog = true)
    @PreAuthorize("hasPermission('system:menu:add')")
    @PostMapping
    public R<Object> add(@Validated @RequestBody SysMenu menu) {
        if (UserConstants.NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu))) {
            return fail("新增菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        } else if (UserConstants.YES_FRAME.equals(menu.getIsFrame())
                && !StringUtils.startsWithAny(menu.getPath(), Constants.HTTP, Constants.HTTPS)) {
            return fail("新增菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
        }
        menu.setCreateBy(Oauth2Utils.getUserName());
        return opResult(menuService.insertMenu(menu));
    }

    /**
     * 修改菜单
     */
    @SystemLog(value = "修改菜单",saveLog = true)
    @PreAuthorize("hasPermission('system:menu:edit')")
    @PutMapping
    public R<Object> edit(@Validated @RequestBody SysMenu menu) {
        if (UserConstants.NOT_UNIQUE.equals(menuService.checkMenuNameUnique(menu))) {
            return fail("修改菜单'" + menu.getMenuName() + "'失败，菜单名称已存在");
        } else if (UserConstants.YES_FRAME.equals(menu.getIsFrame())
                && !StringUtils.startsWithAny(menu.getPath(), Constants.HTTP, Constants.HTTPS)) {
            return fail("修改菜单'" + menu.getMenuName() + "'失败，地址必须以http(s)://开头");
        } else if (menu.getMenuId().equals(menu.getParentId())) {
            return fail("修改菜单'" + menu.getMenuName() + "'失败，上级菜单不能选择自己");
        }
        menu.setUpdateBy(Oauth2Utils.getUserName());
        return opResult(menuService.updateMenu(menu));
    }

    /**
     * 删除菜单
     */
    @SystemLog(value = "删除菜单",saveLog = true)
    @PreAuthorize("hasPermission('system:menu:remove')")
    @DeleteMapping("/{menuId}")
    public R<Object> remove(@PathVariable("menuId") Long menuId) {
        if (menuService.hasChildByMenuId(menuId)) {
            return fail("存在子菜单,不允许删除");
        }
        if (menuService.checkMenuExistRole(menuId)) {
            return fail("菜单已分配,不允许删除");
        }
        return ok(menuService.deleteMenuById(menuId));
    }

    /**
     * 获取路由信息
     *
     * @return 路由信息
     */
    @GetMapping("getRouters")
    public R<List<RouterVo>> getRouters() {
        Long userId = Oauth2Utils.getUserIdLong();
        List<SysMenu> menus = menuService.selectMenuTreeByUserId(userId);
        return ok(menuService.buildMenus(menus));
    }
}
